#include "DatabaseLib.h"
#include <exception>
#include <QDebug>
#include <QString>


const QString g_QPSQL = QString("QPSQL");
const QString g_QMYSQL = QString("QMYSQL");
const QString g_QOCI = QString("QOCI");
const QString g_QODBC = QString("QODBC");
const QString g_QDB2 = QString("QDB2");
const QString g_QTDS = QString("QTDS");
const QString g_QSQLITE = QString("QSQLITE");
const QString g_QIBASE = QString("QIBASE");




bool DatabaseLib::ConnectDB(QStringView _connectName, QStringView filePath, QStringView dbType)
{
	try
	{
		if (QSqlDatabase::database(_connectName.toString()).isOpen())
		{
			m_IsConnect = true;
			return true;
		}
			
		m_db = QSqlDatabase::addDatabase(dbType.toString(), _connectName.toString());
		m_db.setDatabaseName(filePath.toString());
		if (!m_db.open())
		{
			
			qDebug() << "db open failed!"<< m_db.lastError().databaseText();;
			return false;
		}
		m_IsConnect = true;
		return true;
	}
	catch (std::exception* e)
	{
		qDebug() << e->what();
		m_IsConnect = false;
		return false;
	}
	catch (...)
	{
		qDebug() << "other err:" << m_db.lastError();
		m_IsConnect = false;
		return false;
	}
	return true;
}

void DatabaseLib::DisconnectDB(QStringView _connectName) noexcept
{
	QSqlDatabase::database(_connectName.toString()).close();
	QSqlDatabase::removeDatabase(_connectName.toString());
	m_IsConnect = false;
}

QSqlDatabase& DatabaseLib::GetDBInstance()
{
	return m_db;
}

DatabaseLib::DatabaseLib()
	:m_IsConnect{false}
{

}
